
/**
 * 切换页面主题（通过 body class: theme-xxx）
 * @param themeName 主题名称（如 'dark', 'light', 'blue'）
 */
export function switchTheme(themeName) {
  const body = document.body;
  const themeClassPrefix = 'theme-';

  // 1. 过滤掉旧的 theme class
  const currentClasses = Array.from(body.classList);
  const nonThemeClasses = currentClasses.filter(cls => !cls.startsWith(themeClassPrefix));

  // 2. 添加新主题 class
  const newThemeClass = `${themeClassPrefix}${themeName}`;
  nonThemeClasses.push(newThemeClass);

  // 3. 设置回 body.className
  body.className = nonThemeClasses.join(' ');
  localStorage.setItem('agent-app-theme', themeName);
}

export function initTheme() {
  const themeName = localStorage.getItem('agent-app-theme') || 'light';
  switchTheme(themeName);
}

/**
 * 从 URL 渲染 ASCII 图像
 * @param url 图片 URL
 * @param maxWidth 最大宽度（默认 100）
 * @param charsIndex 字符表索引（默认 1）
 */
export function renderAsciiFromUrl({ url, maxWidth = 100, charsIndex = 1 }) {
  return new Promise((resolve, reject) => {
    const img = new Image();
    img.crossOrigin = 'Anonymous'; // 支持跨域图片（如果 CORS 允许）

    img.onload = () => {
      const canvas = document.createElement('canvas');
      const ctx = canvas.getContext('2d');

      // 缩放比例
      const scale = maxWidth / img.width;
      canvas.width = maxWidth;
      canvas.height = img.height * scale;

      // 绘制图片到 canvas
      ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
      const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height).data;

      const chars = grayscaleCharsOptions[charsIndex].value; // 灰度字符表，从浅到深
      let result = '';

      for (let y = 0; y < canvas.height; y++) {
        for (let x = 0; x < canvas.width; x++) {
          const i = (y * canvas.width + x) * 4;
          const r = imageData[i];
          const g = imageData[i + 1];
          const b = imageData[i + 2];
          const avg = (r + g + b) / 3;

          const char = chars[Math.floor(avg / 255 * (chars.length - 1))];
          result += char;
        }
        result += '\n';
      }

      resolve(result);
    };

    img.onerror = () => reject(new Error("Failed to load image"));
    img.src = url;
  });
}

const grayscaleCharsOptions = [
  { label: ' .:-=+*#%@', value: ' .:-=+*#%@' },
  { label: '@%#*+=-:. ', value: '@%#*+=-:. ' },
  { label: ' ⠄⠄⠆⠖⠶⠷⠿⣿', value: ' ⠄⠄⠆⠖⠶⠷⠿⣿' },
  { label: '⣿⠿⠷⠶⠖⠆⠄⠄ ', value: '⣿⠿⠷⠶⠖⠆⠄⠄ ' },
];

/**
 * 分段输出字符串，每段固定长度，间隔一定时间调用输出函数
 * @param {string} text - 原始字符串
 * @param {function(string): void} outputFn - 每段字符的处理函数
 * @param {number} chunkSize - 每段字符数
 * @param {number} interval - 每段输出间隔（毫秒）
 */
export function streamText(text, outputFn, chunkSize = 5, interval = 100) {
  let index = 0;

  const timer = setInterval(() => {
    if (index >= text.length) {
      clearInterval(timer);
      return;
    }
    const chunk = text.slice(index, index + chunkSize);
    outputFn(chunk);
    index += chunkSize;
  }, interval);
}

// 设置全局css变量
export const setGlobalCssVar = (name, value) => {
  const root = document.documentElement;

  // 检查是否已经存在该 CSS 变量
  if (getComputedStyle(root).getPropertyValue(name)) {
    // 如果已经存在，直接修改变量的值
    root.style.setProperty(name, value);
  } else {
    // 如果不存在，添加新的样式规则
    const style = document.createElement("style");
    style.innerText = `
          :root {
              ${name}: ${value};
          }
      `;
    document.head.appendChild(style);
  }
};